<template>
  <el-dialog 
    title="参加订货会/登记销售订单" 
    v-model="visible"
    width="1200px"
    @close="handleCancel"
  >
    <div v-if="currentUser" class="turn-tip">
      {{ isCurrentUser ? '请选择订单' : `等待 ${currentUser} 选择` }}
      <div>当前用户：{{ userInfo?.username }}</div>
      <div>轮次：{{ currentTurn }}</div>
    </div>
    <el-table :data="orderList">
      <el-table-column prop="orderId" label="订单ID" />
      <el-table-column prop="product" label="产品类型" />
      <el-table-column prop="quantity" label="数量" />
      <el-table-column prop="unitPrice" label="单价" />
      <el-table-column prop="totalAmount" label="金额" />
      <el-table-column prop="paymentTerm" label="账期" />
      <el-table-column prop="isoCertification" label="ISO" />
      <el-table-column prop="cost" label="成本" />
      <el-table-column prop="profit" label="利润" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="handleSelect(row.orderId)"
            :disabled="!isCurrentUser"
          >
            选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :disabled="!isConfirmEnabled"
        >
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElDialog, ElTable, ElTableColumn, ElButton } from 'element-plus'
import { ref, computed } from 'vue'
import { get, post } from '@/utils/request'

const visible = ref(false)
const orderList = ref([])
const currentUser = ref(null)
const currentTurn = ref(null)
const gameId = ref('')
const userInfo = JSON.parse(localStorage.getItem('userInfo'))
const emit = defineEmits(['confirm'])

const isCurrentUser = computed(() => {
  return userInfo?.username === currentUser.value
})

const isConfirmEnabled = computed(() => {
  return currentTurn.value > 0 && orderList.value.length === 0
})

const handleSelect = async (orderId) => {
  try {
    await post(`${import.meta.env.VITE_API_BASE_URL}/api/game/${gameId.value}/select-order`, {
      orderId,
      username: userInfo.username
    })
    //  改成通过websocket来刷新订单列表
    // const res = await get(`${import.meta.env.VITE_API_BASE_URL}/api/game/${gameId.value}/available-orders`)
    // orderList.value = res.data.orders
    // currentUser.value = res.data.currentUser
  } catch (e) {
    console.error('选单失败', e)
    alert(e.response?.data?.msg || '选单失败')
  }
}

const show = async (gameIdParam) => {
  try {
    gameId.value = gameIdParam
    const res = await get(`${import.meta.env.VITE_API_BASE_URL}/api/game/${gameIdParam}/available-orders`)
    orderList.value = res.data.orders
    currentUser.value = res.data.currentUser
    currentTurn.value = res.data.currentTurn + 1
    visible.value = true
  } catch (e) {
    console.error('获取订单失败', e)
  }
}

const refreshOrders = async () => {
  try {
    const res = await get(`${import.meta.env.VITE_API_BASE_URL}/api/game/${gameId.value}/available-orders`)
    orderList.value = res.data.orders
    currentUser.value = res.data.currentUser
    currentTurn.value = res.data.currentTurn + 1
  } catch (e) {
    console.error('刷新订单失败', e)
  }
}

const handleCancel = () => {
  visible.value = false
}

const handleConfirm = async () => {
  try {
    // 触发父组件方法
    emit('confirm', '参加订货会/登记销售订单')
    visible.value = false
  } catch (e) {
    console.error('确认操作失败', e)
  }
}

// 暴露刷新方法给父组件
defineExpose({ 
  show,
  refreshOrders 
})
</script>

<style scoped>
.order-dialog {
  width: 90vw; /* 视口宽度的90% */
  max-width: 1200px; /* 最大宽度限制 */
}

.turn-tip {
  margin-bottom: 20px;
  font-size: 16px;
  color: #666;
  font-weight: bold;
}
</style> 